package com.android.vestel.photoroid;

import java.util.ArrayList;

import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;

public class PhotoroidActivity extends PreferenceActivity {
	/** Called when the activity is first created. */
	String ProgramState;
	DataHelper dataHelper;
	boolean checkboxState;
	CheckBoxPreference prefCheckbox;
	ServiceConnection serviceConn;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.setting);

		// is sd card mounted
		if (!isSDCardMounted()) {
			// TODO show alert and close program
			setResult(RESULT_CANCELED);
			finish();
		}

		// create db object and get program state from db
		openDBConnection();
		updateProgramState();
		closeDBConnection();

		PreferenceScreen prefScr = (PreferenceScreen) findPreference("prefMain");
		Preference tempPref = null;
		// picasa preference button
		Preference picasaPref = prefScr.findPreference("picasaPref");
		// flickr preference button
		Preference flickrPref = prefScr.findPreference("flickrPref");
		Preference showPref = prefScr.findPreference("showPref");
		showPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			
			@Override
			public boolean onPreferenceClick(Preference preference) {
//				serviceConn = new ServiceConnection() {
//					@Override
//					public void onServiceDisconnected(ComponentName name) {
//						return;
//					}
//					
//					@Override
//					public void onServiceConnected(ComponentName name, IBinder service) {
//						return;
//					}
//				};
//				Intent intent = new Intent(getBaseContext(),PhotoroidService.class);
//				bindService(intent, serviceConn, Context.BIND_AUTO_CREATE);
//				unbindService(serviceConn);
				Intent serviceIntent = new Intent(getBaseContext(),PhotoroidService.class);
				serviceIntent.putExtra("ForceShowSlide", true);
				startService(serviceIntent);
				return false;
			}
		});
		

		prefCheckbox = (CheckBoxPreference) prefScr
				.findPreference("enableCheckbox");

		OnPreferenceClickListener extDevClickListener = new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
//				Intent extDevFormIntent = new Intent(preference.getContext(),
//						ExternalFormActivity.class);
//				Bundle b = new Bundle();
//				b.putString("externalDeviceIdentifier", preference.getKey()
//						.toString());
//				extDevFormIntent.putExtras(b);
//				startActivityForResult(extDevFormIntent, 0);
				updateProgramState(PhotoroidService.PROG_STAT_EXTERNAL_ENABLED, "external");
				stopService(new Intent(getBaseContext(),PhotoroidService.class));
				startService(new Intent(getBaseContext(),PhotoroidService.class));
				return false;
			}
		};

		picasaPref
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {

					@Override
					public boolean onPreferenceClick(Preference preference) {
						closeDBConnection();
						startActivityForResult(
								new Intent(preference.getContext(),
										PicasaFormActivity.class), 0);
						return false;
					}
				});
		flickrPref
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {

					@Override
					public boolean onPreferenceClick(Preference preference) {
						closeDBConnection();
						startActivityForResult(
								new Intent(preference.getContext(),
										FlickrFormActivity.class), 0);
						return false;
					}
				});

		// set checkbox on change listener
		prefCheckbox
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						Log.e("PhotoroidActivity","Checkbox changed.");
						Log.e("PhotoroidActivity","Old program State = " + ProgramState);
						if (newValue.toString().equals("true")) {// when
																	// checkbox
																	// returns
																	// true
							// TODO: set new program state and enable service
							if (ProgramState
									.equals(PhotoroidService.PROG_STAT_PICASA_DISABLED)) {
								updateProgramState(
										PhotoroidService.PROG_STAT_PICASA_ENABLED,
										"picasa");
							} else if (ProgramState
									.equals(PhotoroidService.PROG_STAT_FLICKR_DISABLED)) {
								updateProgramState(
										PhotoroidService.PROG_STAT_FLICKR_ENABLED,
										"flickr");
							} else if (ProgramState
									.equals(PhotoroidService.PROG_STAT_EXTERNAL_DISABLED)) {
								updateProgramState(
										PhotoroidService.PROG_STAT_EXTERNAL_ENABLED,
										"external");
							} else {
								updateProgramState(
										PhotoroidService.PROG_STAT_DISABLED,
										"null");
								return false;
							}
							startService(new Intent(preference.getContext(),
									PhotoroidService.class));
						} else {
							// TODO: set program state and disable service
							if (ProgramState
									.equals(PhotoroidService.PROG_STAT_PICASA_ENABLED)) {
								updateProgramState(
										PhotoroidService.PROG_STAT_PICASA_DISABLED,
										"picasa");
							} else if (ProgramState
									.equals(PhotoroidService.PROG_STAT_FLICKR_ENABLED)) {
								updateProgramState(
										PhotoroidService.PROG_STAT_FLICKR_DISABLED,
										"flickr");
							} else if (ProgramState.equals(PhotoroidService.PROG_STAT_EXTERNAL_ENABLED)) {
								updateProgramState(
										PhotoroidService.PROG_STAT_EXTERNAL_DISABLED,
										"external");
							} else {
								updateProgramState(
										PhotoroidService.PROG_STAT_DISABLED,
										"null");
								return false;
							}
							stopService(new Intent(preference.getContext(),
									PhotoroidService.class));
						}
						Log.e("PhotoroidActivity","New program State = " + ProgramState);
						return true;
					}
				});

		// set checkbox according to current program state
		updateCheckbox();

		// External Device List
		ArrayList<Preference> extDevicesList = new ArrayList<Preference>();
		tempPref = new Preference(this);
		tempPref.setKey("sdcard");
		tempPref.setTitle("SD Card");
		tempPref.setSummary("Select this device as photosource");
		tempPref.setOnPreferenceClickListener(extDevClickListener);
		extDevicesList.add(tempPref);

		for (int i = 0; i < extDevicesList.size(); i++) {
			prefScr.addPreference(extDevicesList.get(i));
		}
	}

	public static boolean isSDCardMounted() {
		return Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState());
	}
	

	private void updateCheckbox() {
		boolean res = false;
		boolean enabled = false;
		
//		openDBConnection();
//		updateProgramState();
//		openDBConnection();
		
		if (ProgramState.equals("0")) {
			res = false;
			enabled = false;
		} else if (ProgramState
				.equals(PhotoroidService.PROG_STAT_PICASA_DISABLED)
				|| ProgramState
						.equals(PhotoroidService.PROG_STAT_FLICKR_DISABLED)
				|| ProgramState
						.equals(PhotoroidService.PROG_STAT_EXTERNAL_DISABLED)) {
			res = false;
			enabled = true;
		} else if (ProgramState
				.equals(PhotoroidService.PROG_STAT_PICASA_ENABLED)
				|| ProgramState
						.equals(PhotoroidService.PROG_STAT_FLICKR_ENABLED)
				|| ProgramState
						.equals(PhotoroidService.PROG_STAT_EXTERNAL_ENABLED)) {
			res = true;
			enabled = true;
		} else {
			res = false;
			enabled = false;
		}
		prefCheckbox.setChecked(res);
		prefCheckbox.setEnabled(enabled);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == resultCode) {
			updateProgramState();
			updateCheckbox();
		}
	}

	private void openDBConnection() {
		if (dataHelper == null) {
			dataHelper = new DataHelper(this);
		}
	}

	private void closeDBConnection() {
		if (dataHelper != null) {
			dataHelper.closeDB();
			dataHelper = null;
		}
	}

	private String updateProgramState() {
		openDBConnection();
		ProgramState = dataHelper.selectAllOfSetting().get(
				DataHelper.PROGRAM_STATE);
		closeDBConnection();
		return ProgramState;
	}

	private void updateProgramState(String newProgramState,
			String newServiceProvider) {
		ProgramState = newProgramState;
		openDBConnection();
		dataHelper.updateSettingTable(newProgramState, newServiceProvider);
		closeDBConnection();
	}
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		closeDBConnection();
		//unbindService(serviceConn);
	}
}